//
//  PersonelController.m
//  TinyFortune
//
//  Created by lc on 16/5/25.
//  Copyright © 2016年 lc. All rights reserved.
//
//
//  MyViewController.m
//  TinyFortune
//
//  Created by lc on 16/5/19.
//  Copyright © 2016年 lc. All rights reserved.
//

#import "PersonelController.h"
#import "UIImage + blur.h"
#import "AVFile +  getDictionary.h"
#import "tinyDataModel.h"
#import "tinyFrameModel.h"
#import "loginViewController.h"
#import "tintyCell.h"
#define  LC_header 140


NSString *const myViewCellIdentifier = @"myViewCell";

@interface PersonelController ()<UITableViewDataSource,UITableViewDelegate>{
}
@end


@implementation PersonelController

- (instancetype)init{
    if (self = [super init]) {
        _loversId = [AVUser currentUser].mobilePhoneNumber;
    }
    return self;
}
#pragma mark - 懒加载
- (NSMutableArray *)MyViewDataArray{
    if (!_MyViewDataArray) {
        _MyViewDataArray = [NSMutableArray new];
    }
    return _MyViewDataArray;
}
- (NSMutableArray *)frameArray{
    if (!_frameArray) {
        _frameArray = [NSMutableArray new];
    }
    return _frameArray;
}
- (AFHTTPSessionManager *)httpManager{
    if (!_httpManager) {
        _httpManager = [AFHTTPSessionManager manager];
        _httpManager.responseSerializer = [AFJSONResponseSerializer serializer ];
        _httpManager.responseSerializer.acceptableContentTypes = [_httpManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    }
    return _httpManager;
}

#pragma mark - 配置collectionView
- (void)configurationCollectionView{
    
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    [self getAllTalk];
}


#pragma mark -界面搭建
- (void)createUI{
    CGFloat margin = 10 ;
    
    //隐藏导航栏
    [self.navigationController.navigationBar setHidden:YES];
    
    self.MyViewTableView = [UITableView new];
    _MyViewTableView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.MyViewTableView];
    __weak typeof (self)weakSelf = self;
    [self.MyViewTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view.mas_top).offset(0);
        make.left.equalTo(weakSelf.view.mas_left);
        make.right.equalTo(weakSelf.view.mas_right);
        make.bottom.equalTo(weakSelf.view.mas_bottom);
    }];
    self.MyViewTableView.delegate = self ;
    self.MyViewTableView.dataSource = self ;
    self.MyViewTableView.rowHeight = LC_header ;
    
    
    
    //让-20为起始点的offset，为了简化数学上的判断过程！！
    [_MyViewTableView setContentInset:UIEdgeInsetsMake(-20, 0, 0, 0)];
    //对整个TableView注测观察者
    [_MyViewTableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
    
    
    //头视图
    _header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, LC_WIDTH, LC_header + 65)];
    // _header.backgroundColor = [UIColor yellowColor];
    _headerView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, LC_WIDTH, LC_header)];
    _headerView.image = [UIImage imageNamed:@"IMG_2455.JPG"];
    [_header addSubview:self.headerView];
    [self.MyViewTableView setTableHeaderView:_header];
    
    _header.clipsToBounds = NO;
    //头像
    self.iconImage = [[UIImageView alloc]initWithFrame:CGRectMake(10, self.headerView.frame.size.height +self.headerView.frame.origin.y - 35, 70, 70)];
    //获取当前用户头像
    AVFile *file = [[AVUser currentUser] objectForKey:@"iconImage"];
    NSDictionary *dict = [AVFile fileWithDictionary:file];
    [self.iconImage sd_setImageWithURL:[NSURL URLWithString:dict[@"url"]]];
    
    
    [_header addSubview:self.iconImage];
    
    
    self.iconImage.layer.cornerRadius = 10;
    self.iconImage.layer.borderColor = [UIColor whiteColor].CGColor;
    self.iconImage.layer.borderWidth = 2;
    self.iconImage.layer.masksToBounds = YES;
    //黑体字
    self.blackLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, self.iconImage.frame.size.height + self.iconImage.frame.origin.y + margin , 150, 20)];
    [_header addSubview:_blackLabel];
    _blackLabel.text = [AVUser currentUser].username;
    _blackLabel.textColor = [UIColor blackColor];
    _blackLabel.font = [UIFont systemFontOfSize:18];
    
    //白体字
    _whiteLabel = [[UILabel alloc]initWithFrame:CGRectMake(LC_WIDTH/2.0f - 75, _header.frame.size.height+_header.frame.origin.y, 150, 20)];
    _whiteLabel.textAlignment = NSTextAlignmentCenter;
    [_header addSubview:_whiteLabel];
    _whiteLabel.text = [AVUser currentUser].username ;
    NSLog(@"%@",_whiteLabel.text);
    _whiteLabel.textColor = [UIColor whiteColor];
    _whiteLabel.font = [UIFont systemFontOfSize:20];
    _whiteLabel.alpha = 0;//先让白色Label透明
    //这里准备一些模糊的照片
    self.blurImageArray = [NSMutableArray new];
    //    for (int i = 0; i < 2; i ++) {
    //        UIImage *image = [self.headerView.image boxblurImageWithBlur:0.1 * i];
    //        [self.blurImageArray addObject:image];
    //    }
    
    [self.blurImageArray addObject:self.headerView.image];
    [self.blurImageArray addObject:[self.headerView.image boxblurImageWithBlur:1]];
    
    //添加滑动手势
    UISwipeGestureRecognizer *rightSwip = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(rightGo)];
    [rightSwip setDirection:UISwipeGestureRecognizerDirectionLeft];
    [self.view addGestureRecognizer:rightSwip];
    
}
#pragma mark - 添加左滑手势
- (void)rightGo{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 观察者模式
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    //定义需要的变量
    CGFloat margin = 10;//间距
    UITableView *tableView = (UITableView *)object;
    CGFloat offset = tableView.contentOffset.y;//偏移量
    
    //    NSInteger blur = offset / 10 ;
    //    if (offset < 0) {
    //        blur = 0;
    //    }else if(offset > 90){
    //        blur = 9 ;
    //    }
    
    //开始的toffset = offset = 0
    //如果toffset比上一个offset大的话，就是说明当前正在向上走
    if ( offset >= 0  && self.tOffset < offset){
        _up = YES ;
    }
    else if (offset < 0 && self.tOffset > offset) {
        _up = YES;
    }else{
        _up = NO ;
    }
    
    NSLog(@"!!%lf",tableView.contentOffset.y);
    
    //下拉的时候头视图放大，其他视图回到原位
    if (offset < 0) {
        [_header bringSubviewToFront:_iconImage];
        self.headerView.frame = CGRectMake(offset, offset, LC_WIDTH - 2 * offset, LC_header - offset);
        self.iconImage.frame = CGRectMake(10, self.headerView.frame.size.height +self.headerView.frame.origin.y - 35, 70, 70);
        self.blackLabel.frame = CGRectMake(5, self.iconImage.frame.size.height + self.iconImage.frame.origin.y + margin , 150, 20);
        self.whiteLabel.frame = CGRectMake(LC_WIDTH/2.0f - 75, _header.frame.size.height + _header.frame.origin.y, 150, 20);
        self.followButton.frame = CGRectMake(LC_WIDTH - 120 - margin , _headerView.frame.origin.y + _headerView.frame.size.height + margin, 120, 30) ;
               self.headerView.image = self.blurImageArray[0];
    }
    //1.上拉的时候头像缩小且往下走
    else if(offset >= 0  && self.iconImage.frame.size.width >= 45 && self.iconImage.frame.origin.y + self.iconImage.frame.size.height > _headerView.frame.size.height +_header.frame.origin.y  ) {
        
        //这是上拉时候的情况
        if(self.up){
            //头视图向上走
            self.headerView.frame = CGRectMake(_headerView.frame.origin.x, _headerView.frame.origin.y -  0.14 *offset, _headerView.frame.size.width, _headerView.frame.size.height);
            
            //头像缩小且往下走
            self.iconImage.frame = CGRectMake(self.iconImage.frame.origin.x, self.iconImage.frame.origin.y , self.iconImage.frame.size.width - offset * 0.1 , self.iconImage.frame.size.height - offset * 0.1);
            
            //黑label往上走
            self.blackLabel.frame = CGRectMake(self.blackLabel.frame.origin.x, self.blackLabel.frame.origin.y - offset * 0.1, self.blackLabel.frame.size.width, self.blackLabel.frame.size.height);
            //粉丝按钮向上走
            self.followButton.frame = CGRectMake(self.followButton.frame.origin.x, self.followButton.frame.origin.y - offset * 0.1, self.followButton.frame.size.width, self.followButton.frame.size.height);
                    }
        //这是下拉时候的情况
        else{
            self.whiteLabel.alpha = 0;
            //头视图向下走
            self.headerView.frame = CGRectMake(_headerView.frame.origin.x, _headerView.frame.origin.y + offset * 0.14 , _headerView.frame.size.width, _headerView.frame.size.height );
            
            
            //头像放大且往上走
            self.iconImage.frame = CGRectMake(self.iconImage.frame.origin.x, self.iconImage.frame.origin.y , self.iconImage.frame.size.width + offset * 0.1 , self.iconImage.frame.size.height + offset * 0.1);
            
            //黑label往下走
            self.blackLabel.frame = CGRectMake(self.blackLabel.frame.origin.x, self.blackLabel.frame.origin.y +
                                               offset * 0.1, self.blackLabel.frame.size.width, self.blackLabel.frame.size.height);
            //追随按钮往下走
            self.followButton.frame = CGRectMake(self.followButton.frame.origin.x, self.followButton.frame.origin.y + offset * 0.1, self.followButton.frame.size.width, self.followButton.frame.size.height);
            //分栏控制器往下走
           
        }
        
        
    }//2.头像缩小到一定程度之后往上走
    else if(offset >= 15 && self.iconImage.frame.size.width < 45 &&self.blackLabel.frame.origin.y + self.blackLabel.frame.size.height  + margin > _headerView.frame.size.height + _headerView.frame.origin.y && self.up){
        
        //让头像隐藏在下面
        [_header bringSubviewToFront:_headerView ];
        //让白色露出来
        [_header insertSubview:_whiteLabel aboveSubview:_headerView];
        
        //头像往上走
        self.iconImage.frame = CGRectMake(self.iconImage.frame.origin.x, self.iconImage.frame.origin.y - offset * 0.2, self.iconImage.frame.size.width, self.iconImage.frame.size.height);
        //blackLabel往上走
        self.blackLabel.frame = CGRectMake(self.blackLabel.frame.origin.x, self.blackLabel.frame.origin.y - offset * 0.2, self.blackLabel.frame.size.width, self.blackLabel.frame.size.height);
        //当balckLabel走到与headerView相交时，whiteLabel出现，并且马上显示
        if (self.blackLabel.frame.origin.y <= _headerView.frame.size.height + _headerView.frame.origin.y) {
            self.whiteLabel.alpha = 1;
            NSLog(@"此时头视图y坐标%lf",_headerView.frame.origin.y );
            self.whiteLabel.frame = CGRectMake(self.whiteLabel.frame.origin.x, self.blackLabel.frame.origin.y, self.whiteLabel.frame.size.width, self.whiteLabel.frame.size.height);
#pragma mark - 模糊处理，这里还需要修改
            self.headerView.image = self.blurImageArray[1];
        }
        
    }
    //3.最后,当往下拉的时候
    else if(self.iconImage.frame.size.width <45   && offset > 0 &&self.iconImage.frame.origin.y  < _headerView.frame.origin.y + _headerView.frame.size.height && !_up ){
        
        //头像往下走
        self.iconImage.frame = CGRectMake(self.iconImage.frame.origin.x, self.iconImage.frame.origin.y + offset * 0.1, self.iconImage.frame.size.width, self.iconImage.frame.size.height);
        //blackLabel往下走
        self.blackLabel.frame = CGRectMake(self.blackLabel.frame.origin.x, self.blackLabel.frame.origin.y + offset * 0.1, self.blackLabel.frame.size.width, self.blackLabel.frame.size.height);
        
        //当balckLabel走到与headerView相交时，whiteLabel 逐渐消失
        if (self.blackLabel.frame.origin.y < _headerView.frame.size.height + _headerView.frame.origin.y) {
            NSLog(@"测试Alpha,此时 %lf %lf",self.blackLabel.frame.origin.y,_headerView.frame.size.height + _headerView.frame.origin.y);
            self.whiteLabel.alpha = 1;
            self.whiteLabel.frame = CGRectMake(self.whiteLabel.frame.origin.x, self.blackLabel.frame.origin.y, self.whiteLabel.frame.size.width, self.whiteLabel.frame.size.height);
            self.headerView.image = self.blurImageArray[1];
        }
        if (self.blackLabel.frame.origin.y >= _headerView.frame.size.height + _headerView.frame.origin.y) {
            self.whiteLabel.alpha = 0 ;
        }
    }
    //4.最后一步,头像放大
    else if(self.iconImage.frame.size.width < 70 && offset > 0 && self.iconImage.frame.origin.y > _headerView.frame.size.height  + _headerView.frame.origin.y && !_up &&offset <40){
        self.whiteLabel.alpha = 0;
        self.headerView.image = self.blurImageArray[0];
        [_header bringSubviewToFront:_iconImage];
        //        self.iconImage.frame = CGRectMake(self.iconImage.frame.origin.x, self.iconImage.frame.origin.y, self.iconImage.frame.size.width +offset * 0.6, self.iconImage.frame.size.height+ offset * 0.6);
        //
    }
    //
    
    self.tOffset = offset;
    
}

//MARK:注销观察者
- (void)dealloc{
    [_MyViewTableView removeObserver:self forKeyPath:@"contentOffset"];
}


#pragma mark - 实现协议
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return  [self.frameArray[indexPath.row] cellHeight];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.MyViewDataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    tintyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[tintyCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
        
        
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.dataModel = self.MyViewDataArray[indexPath.row];
    cell.frameModel = self.frameArray[indexPath.row];
    return cell;
}

#pragma mark -获取所有发过的说说
- (void)getAllTalk{
    __weak typeof(self)weakSelf = self;
    //先找ID表
    AVQuery *query = [[AVQuery alloc]initWithClassName:@"ID"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        //再找file
        for (AVObject *obc in objects) {
            [AVFile getFileWithObjectId:[obc objectForKey:@"ID"] withBlock:^(AVFile *file, NSError *error) {
              
                if([file.metaData[@"username"] isEqualToString:_loversId]){
                    NSDictionary *dict = [AVFile fileWithDictionary:file];
                    tinyDataModel *model = [[tinyDataModel alloc]initWithDict:dict];
                    [weakSelf.MyViewDataArray addObject: model];
                    tinyFrameModel *frame = [tinyFrameModel new];
                    frame.dataModel = model;
                    [weakSelf.frameArray addObject:frame];
                    [self.MyViewTableView reloadData];
                }

            }];
            
            
        }
    }];
    
    //刷新
    dispatch_async(dispatch_get_main_queue(), ^{
        
    });
}




@end
